package com.hs.pre.search;

import java.awt.Font;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.category.DefaultCategoryDataset;

import cn.ac.cintcm.prespring.statistics.GXstatistics;
import cn.ac.cintcm.prespring.statistics.ZYstatistics;
import cn.ac.cintcm.prespring.statistics.ZZstatistics;

import com.hs.common.JSONHandle;
import com.hs.core.action.BaseAction;
import com.hs.log.HsLogger;

/**
 * for zy/zz/gx statistics in a fangji collection
 * @author CaoMudan on 2008-10-27
 *
 */
public class StatisticsAction  extends BaseAction{
	private static final HsLogger logger = HsLogger.getLogger(StatisticsAction.class.getName());
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse rsp) throws Exception { 
	
		String ids = req.getParameter("fjids");
		if (ids == null || ids.length() == 0) {
			return null;
		}
		/***
		 * 需要显示的图片对象集合
		 */
		List imageView = new ArrayList();
		logger.info("statistics --- fjids are "+ids);
		List<String> fjids = new ArrayList<String>();
		String[] fids = ids.split(",");
		for (int i = 0; i < fids.length; i++) {
			fjids.add(fids[i]);
		}
		ZZstatistics zz = new ZZstatistics();
		Map<String, Integer> zzMap = zz.getStatisticalData(fjids);

		ZYstatistics zy = new ZYstatistics();
		Map<String, Integer> zyMap = zy.getStatisticalData(fjids);

		GXstatistics gx = new GXstatistics();
		Map<String, Integer> gxMap = gx.getStatisticalData(fjids);

		logger.info("statistics result----zz:"+zzMap.size()+" zy:"+zyMap.size()+" gx:"+gxMap.size());
		// plot zhongyao distribution graph
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		BarRenderer3D renderer = new BarRenderer3D();
		renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		renderer.setItemLabelFont(new Font("宋体", Font.PLAIN, 12));
		renderer.setItemLabelsVisible(true);
		
		
		StatImage statImage = this.getStatImage(renderer, req, zzMap, dataset);
		statImage.setImageType("zzGraph");
		imageView.add(statImage);
		statImage = this.getStatImage(renderer, req, zyMap, dataset);
		statImage.setImageType("zyGraph");
		imageView.add(statImage);
		statImage = this.getStatImage(renderer, req, gxMap, dataset);
		statImage.setImageType("gxGraph");
		imageView.add(statImage);
		JSONHandle jSONHandle = new JSONHandle();
		String outStr = jSONHandle.getJsonToStr(imageView);
		rsp.getOutputStream().println(outStr);
		rsp.flushBuffer();
		
		//return mapping.findForward("success");
		return null;
	}
	
	/**
	 * 生成统计图
	 * @param renderer
	 * @param req
	 * @param dataMap 被统计数据
	 * @param dataset
	 * @return
	 * @throws IOException
	 */
	private StatImage getStatImage(BarRenderer3D renderer,HttpServletRequest req,Map<String, Integer> dataMap,DefaultCategoryDataset dataset) throws IOException{
		dataset.clear();
		Set<String> keys = dataMap.keySet();
		Iterator iter = keys.iterator();
		Integer count=1;
		while (iter.hasNext()) {
			String name = iter.next().toString();
			if(dataMap.get(name)>1){
				System.out.println("name:" + name);
				dataset.addValue(dataMap.get(name), count+":"+name, count);
				count++;
			}						
		}
		if(count<10){
			iter = keys.iterator();
			while (iter.hasNext() && (count<=10)) {
				String name = iter.next().toString();
				if(dataMap.get(name)==1){
					dataset.addValue(dataMap.get(name), count+":"+name, count);
					count++;
				}						
			}
		}
		JFreeChart zyChart = ChartFactory.createBarChart3D("", "",
				"", dataset, PlotOrientation.VERTICAL, true, false, false);
		
		CategoryPlot plot = (CategoryPlot) zyChart.getPlot();
		NumberAxis  axis = (NumberAxis)plot.getRangeAxis();   
		axis.setTickUnit(new NumberTickUnit(1D));
		plot.setRenderer(renderer);
		plot.setForegroundAlpha(0.6f);
		String filename = ServletUtilities.saveChartAsPNG(zyChart, 600, 300,
				null, req.getSession());
		String filename02 = ServletUtilities.saveChartAsPNG(zyChart, 200, 100,
				null, req.getSession());
		String graphURL = req.getContextPath() + "/DisplayChart?filename="+ filename;
		StatImage  graph = new StatImage();
		graph.setImageName(filename);
		graph.setImageUrl(graphURL);
		return graph;
	}

}
